package com.xin.di.uav.applet.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/sys/oss")
public class OssController {

    @Value("${oss.endpoint:oss-cn-beijing.aliyuncs.com}")
    private String endpoint;

    @Value("${oss.accessKeyId:LTAI5tCpX6nRTEosndGR9CKx}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret:xXgpo2l3ocEVux5SwDEFSzPhJwr05D}")
    private String accessKeySecret;
//
//    @Value("${oss.bucketName:public-uav-img}")
//    private String bucketName;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("files") MultipartFile file, @RequestParam String bucketName) {
        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 上传文件流
            ossClient.putObject(bucketName, fileName, file.getInputStream());

            // 关闭OSSClient
            ossClient.shutdown();

            // 返回文件访问路径
            String fileUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return ResponseEntity.ok(fileUrl);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("上传失败");
        }
    }
}
